package bday.tvlport.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

public class LoggerUtility {
	private static LoggerUtility instance;
	protected LoggerUtility()
	{
		// Only to Defeat Instantiation.
	}
	 public static synchronized LoggerUtility getInstance() 
	 // only one instance of log would be created at a time
	 {
	      if(instance == null) {
	         instance = new LoggerUtility();
	      }
	      return instance;
	 }

	static SimpleDateFormat df = new SimpleDateFormat("[ dd-MM-yyyy HH:mm:ss ]");

	static Logger logger = Logger.getLogger("SimpleLayoutExample.class");

	private static void log(String s, int i) {
		String time = df.format(new Date());
		String dt = time.substring(2, 12);
		try {
			FileAppender fileappender = new FileAppender(new SimpleLayout(), "/Logs/Log_" + dt + ".log");
			logger.addAppender(fileappender);
			HttpSession session = null;
			
			if (i == 0) {
				logger.info(time + s);
			}
			else if (i == 1) {
				logger.warn(time + s);
			}
			else if (i == 2) {
				if(FacesContext.getCurrentInstance() != null) {
					session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
					session.setAttribute("error", time + s);
				}
				logger.error(time + s);
			}
			logger.removeAppender(fileappender);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void info(String s) {
		log(s, 0);
	}
	
	public static void warn(String s) {
		log(s, 1);
	}
	
	public static void error(String s) {
		log(s, 2);
	}
}
